package org.example.demo.apiv2.sql;

import cn.hutool.core.collection.CollectionUtil;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.schema.Column;
import net.sf.jsqlparser.statement.select.OrderByElement;
import org.example.demo.apiv2.constant.OrderType;
import org.example.demo.apiv2.entity.OrderEntity;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class OrderParser {

    /**
     * 构造jsqlparser的OrderByElement对象集合
     *
     * @param orderEntity
     * @return
     */
    public static OrderByElement getOrderByElement(OrderEntity orderEntity) {
        Column column = FieldParser.getColumn(orderEntity.getField());
        OrderByElement orderByElement = new OrderByElement();
        orderByElement.setExpression(column);
        String order = orderEntity.getOrder();
        switch (order) {
            case OrderType.ASC:
                orderByElement.setAsc(true);
                break;
            case OrderType.DESC:
                orderByElement.setAsc(false);
                break;
            default:
                log.error("不支持的排序规则: {}", order);
                throw new IllegalArgumentException("不支持的排序规则: " + order);
        }
        return orderByElement;
    }


    /**
     * 构造jsqlparser的OrderByElement对象集合
     *
     * @param orderEntityList
     * @return
     */
    public static List<OrderByElement> getOrderByElementList(List<OrderEntity> orderEntityList) {
        if (CollectionUtil.isEmpty(orderEntityList)) {
            return new ArrayList<>();
        }
        List<OrderByElement> orderByElementList = new ArrayList<>();
        for (OrderEntity orderEntity : orderEntityList) {
            OrderByElement orderByElement = getOrderByElement(orderEntity);
            orderByElementList.add(orderByElement);
        }
        return orderByElementList;
    }
}
